package com.jd.dlc.spring;

import com.jd.dlc.util.CaseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author sizegang1
 * @date 2022-01-27 23:56 2022-01-27 23:56
 */
public class SpringUtils implements ApplicationContextAware {

    static  Logger logger = LoggerFactory.getLogger(SpringUtils.class);

    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        try {
            return getApplicationContext().getBean(CaseUtil.toHumpCamlCase(name));
        }catch (Exception exception){
            logger.error("Dlc getBean is null error {}", exception);
            return null;
        }
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {

        try {
            return getApplicationContext().getBean(clazz);
        }catch (Exception exception){
//            logger.error("Dlc getBean is null error {}", exception);
            return null;
        }
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        try {
            return getApplicationContext().getBean(CaseUtil.toHumpCamlCase(name), clazz);
        }catch (Exception exception){
//            logger.error("Dlc getBean is null error {}", exception);
            return null;
        }
    }

    //通过class获取Bean.
    public static Map<String,Object> getBeansWithAnnotation(Class clazz) {

        try {
            return getApplicationContext().getBeansWithAnnotation(clazz);
        }catch (Exception exception){
//            logger.error("Dlc getBean is null error {}", exception);
            return null;
        }
    }
}
